package com.longshihan.lifecycler.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.graphics.Xfermode;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import com.longshihan.lifecycler.R;

/**
 * Created by LONGHE001.
 *
 * @time 2019/5/30 0030
 * @des
 * @function
 */

public class TineView extends View {
    private Paint mPaint;
    private Bitmap srcBmp;
    private RectF dstRect;
    private int currentModeY = 15;
    private Xfermode mXfermode;
    private PorterDuff.Mode mPorterDuffMode = PorterDuff.Mode.SRC_ATOP;


    public TineView(Context context) {
        super(context);
        init(context);
    }

    public TineView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public TineView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    public void init(Context context) {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
        srcBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.icon_commonheader_bottom);
        mXfermode = new PorterDuffXfermode(mPorterDuffMode);
        mPaint.setColor(Color.BLUE);

    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int layerID = canvas.saveLayer(0,0,getWidth(),getHeight(),mPaint,Canvas.ALL_SAVE_FLAG);
        dstRect = new RectF(0, 0, getWidth(), currentModeY);
        //设置混合模式
        canvas.drawBitmap(srcBmp, 0, 0, null);
        mPaint.setXfermode(mXfermode);
        canvas.drawRect(dstRect, mPaint);
        //清除混合模式
        mPaint.setXfermode(null);
        canvas.restoreToCount(layerID);
    }

    public void setCurrentModeY(int currentModeY) {
        this.currentModeY = currentModeY;
        postInvalidate();
    }
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        int width = srcBmp.getWidth();
        int height = srcBmp.getHeight();
        // 计算缩放比例
        float scaleWidth = ((float) w) / width;
        float scaleHeight = ((float) h) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        srcBmp = Bitmap.createBitmap(srcBmp, 0, 0, width, height, matrix, true);
    }
}
